package models

import (
	"fmt"
)

type Resource struct {
	Rid int
	Cnname string
	Enname string
	Aliasname string
	Remark string
	ResourceType int
	Category string
	Area string
	Lang string
	Format string
	PublishYear string
	Tvstation int
	PlayStatus string
	Zimuzu string
	RenewStatus string
	RenewStatusTime string
	Rank int
	RankValue float64
	Poster string
	PremiereTime string
	PlayTime int
	Views int
	Favorites int
	Score float32
	OperatorId int
	Status int
	UpdateTime string
	CreateTime string
}

func (Resource) TableName() string {
	return "resource"
}

func GetResourceAreaFromId(id int) string {
	var resource Resource
	db.Where(&Resource{Rid:id}).First(&resource)
	return resource.Area
}

func GetHotResource(hot int) (resource []Resource){
	db.Where(&Resource{Status:1}).Order("rank asc", true).Limit(hot).Find(&resource)
	return
}

func GetResourceByRid(Rid int) (resource Resource){
	db.Where(&Resource{Rid:Rid}).First(&resource)
	return
}

type ResourceReturn struct {
	Rid,Views,Favorites,Rank int
	CnName,EnName,PlayStatus,Poster,PublishYear string
	Area,TvStation,Type,Category,Lang,Remark string
	PremiereTime,PremiereStatus,UpdateTime string
	Score float32
}

func GetResourceByParams(params interface{}, page int, pageSize int) (resource []Resource) {

	// 数据库
	DB := db

	// 解析参数
	temp := params.(map[string]interface{})
	for kk, value := range temp{
		if kk == "Category" {
			switch tempType := value.(type) {
			case string:
				DB = DB.Where("Category like ?", "%"+tempType+"%")
			default:
				fmt.Println("unknown Category: ", value)
			}
		}else if kk == "TypeId"{
			switch tempType := value.(type) {
			case string:
				DB = DB.Where("resource_type in (?)", []string{"", "0", tempType})
			case int:
				DB = DB.Where("resource_type in (?)", []int{0, tempType})
			default:
				fmt.Println("unknown resource_type: ", value)
			}
		}else if kk == "Area"{
			switch tempType := value.(type) {
			case string:
				DB = DB.Where("area in (?)", []string{"", tempType})
			default:
				fmt.Println("unknown Area: ", value)
			}
		}else if kk == "PublishYear"{
			switch tempType := value.(type) {
			case int:
				DB = DB.Where("publish_year in (?)", []int{0, tempType})
			case int64:
				DB = DB.Where("publish_year in (?)", []int64{0, tempType})
			case string:
				DB = DB.Where("publish_year in (?)", []string{"0", tempType})
			default:
				fmt.Println("unknown PublishYear: ", value)
			}
		}else if kk == "TvStation"{
			switch tempType := value.(type) {
			case int:
				DB = DB.Where("tvstation in (?)", []int{0, tempType})
			default:
				fmt.Println("unknown TvStation: ", value)
			}
		}
	}

	// 取 resource 数据库 数据
	DB.Limit(pageSize).Offset((page - 1) * pageSize).Find(&resource)
	return
}